<?php

class VacCodeVerifyPage extends Page
{

}

class VacCodeVerifyPage_Controller extends Page_Controller
{
    private static $allowed_actions = array(
        "Form"
    );

    public function Form()
    {
        $fields = new FieldList
        (
            new TextField("TagCode", _t("General.ENTER_TAG_CODE", "Enter Code"))
        );

        $actions = new FieldList(new FormAction("DoVerify", _t("General.SUBMIT", "Submit")));
        $validator = new RequiredFields("TagCode");

        return new Form($this, "Form", $fields, $actions, $validator);
    }

    public function DoVerify($data, $form)
    {
        $hasError = false;
        $tagCode = $data["TagCode"];

        if (strlen($tagCode) > 10) {
            $form->addErrorMessage("Username", _t("General.TAG_CODE_INVALID", "Invalid code."), Globals::STATUS_BAD);
            $hasError = true;
        }

        if ($hasError) {
            Session::set("FormInfo.Form_RegistrationForm.data", $data); // Retain form data for correction.
            return $this->redirectBack();
        }

        $vacTag = VacTag::get()->filter(
            array(
                "TagCode" => $tagCode
            )
        )->first();

        if ($vacTag) {
            // Tag found.
            $deactivateOnVerify = true;
            $tagStatus = ""; // Reference for tag code status.
            $vacTag->isTagValid($deactivateOnVerify, true, $tagStatus);

            if ($tagStatus == Globals::STATUS_ACTIVE) {
//                $message = _t("General.TAG_CODE_INVALID", "Code is valid.");
                $message = "Code is valid.";
            } elseif ($tagStatus == Globals::STATUS_EXPIRED) {
                $message = _t("General.TAG_CODE_EXPIRED", "Code is expired.");
            } else {
                $message = _t("General.TAG_CODE_INVALID", "Invalid code.");
            }
        } else {
            $message = _t("General.TAG_CODE_INVALID", "Invalid code.");
        }

        $this->setFlashMessage($message, ($tagStatus == Globals::STATUS_ACTIVE ? Globals::STATUS_SUCCESS : Globals::STATUS_BAD));
        return $this->redirectBack();
    }
}